Fix image flickering in Firefox

Problem

Image flickers/flashes when image.src gets updated in Firefox >= 8.0. There has already been a bug filed against it and I have encountered this issue in my own project as well.

Solution

Assuming we have a tartget image element and a new image source we want to update to, the fix, or more precisely workaround, is to force compute a hidden image with new source in DOM before we update the actual image src:

const parentNode = image.parentNode

// Create a hidden image clone
const temp = image.cloneNode(false)
temp.setAttribute('src', source)
temp.style.position = 'fixed'
temp.style.visibility = 'hidden'

parentNode.appendChild(temp)

// Delay is necessary to prevent image from flickering
setTimeout(() => {
  // Update actual image src
  image.setAttribute('src', source)

  // Remove clone afterwards
  parentNode.removeChild(temp)
}, 50)